package com.dragonsen.log;

import com.android.build.gradle.AppExtension;
import com.android.build.gradle.AppPlugin;
import com.android.build.gradle.LibraryExtension;
import com.dragonsen.log.datascantrans.DataScanAppTransform;
import com.dragonsen.log.datascantrans.DataScanLibraryTransform;
import com.dragonsen.log.datascantrans.DataScanTransform;
import com.dragonsen.log.logtrans.LogAppTransform;
import com.dragonsen.log.logtrans.LogLibraryTransform;

import org.gradle.api.Plugin;
import org.gradle.api.Project;

public class LogPlugin implements Plugin<Project> {

    private static final String EXT_NAME = "log";

    @Override
    public void apply(Project project) {
        boolean isApp = project.getPlugins().hasPlugin(AppPlugin.class);
        project.getExtensions().create(EXT_NAME, LogConfig.class);
        project.afterEvaluate(project1 -> {
            LogConfig config = (LogConfig) project1.getExtensions().findByName(EXT_NAME);
            if (config == null) {
                config = new LogConfig();
            }
            config.transform();
        });
        //app
        if (isApp) {
            AppExtension appExtension = project.getExtensions().getByType(AppExtension.class);
            //日志Transform
            appExtension.registerTransform(new LogAppTransform());
            //数据扫描
            DataScanTransform scanTransform = new DataScanAppTransform();
            appExtension.registerTransform(scanTransform);
            return;
        }
        //lib
        if (project.getPlugins().hasPlugin("com.android.library")) {
            LibraryExtension libraryExtension = project.getExtensions().getByType(LibraryExtension.class);
            //日志Transform
            libraryExtension.registerTransform(new LogLibraryTransform());
            //数据扫描
            DataScanTransform scanTransform = new DataScanLibraryTransform();
            libraryExtension.registerTransform(scanTransform);
        }
    }
}
